﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Configuration;
using de.rwth.rz.campus.labs.Mailer2010.SPHelper;
using System.Web.UI.WebControls;

namespace de.rwth.rz.campus.labs.Mailer2010
{
    public class GroupField : SPFieldMultiColumn
    {
        public GroupField(SPFieldCollection fields, string fieldName) : base(fields, fieldName) { }
        public GroupField(SPFieldCollection fields, string fieldName, string displayName) : base(fields, fieldName, displayName) { }

        /// Override, to tell Sharepoint which control to use to render the field
        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                BaseFieldControl control = new GroupFieldControl();
                control.FieldName = this.InternalName;
                return control;
            }
        }

        public override string GetValidatedString(object value)
        {
            return base.GetValidatedString(value);
        }
    }

    public class GroupFieldControl : BaseFieldControl
    {
        protected InputFormCheckBoxList GroupSelector;


        protected override string DefaultTemplateName
        {
            get
            {
                return @"GroupFieldTemplate";
            }
        }

        public override void Validate()
        {
            if ((base.ControlMode != SPControlMode.Display) && base.IsValid)
            {
                base.Validate();
                if (base.Field.Required && (this.GroupSelector.SelectedIndex == -1))
                {
                    base.IsValid = false;
                    base.ErrorMessage = SPResource.GetString("MissingRequiredField", new object[0]);
                }
            }
        }

        public override object Value
        {
            get
            {
                EnsureChildControls();
                SPFieldMultiColumnValue fieldValue = new SPFieldMultiColumnValue();
                for (int i = 0; i < GroupSelector.Items.Count; i++)
                {
                    if (GroupSelector.Items[i].Selected) { fieldValue.Add(GroupSelector.Items[i].Value); }
                }

                return fieldValue;
            }
            set
            {
                EnsureChildControls();
                GroupSelector.ClearSelection();

                SPFieldMultiColumnValue fieldValue = (SPFieldMultiColumnValue)value;
                for (int i = 0; i < fieldValue.Count; i++)
                {
                    if (GroupSelector.Items.FindByValue(fieldValue[i]) != null)
                        GroupSelector.Items.FindByValue(fieldValue[i]).Selected = true;
                }
            }
        }


        protected override void CreateChildControls()
        {
            if (this.Field == null || this.ControlMode == SPControlMode.Display)
                return;

            base.CreateChildControls();
            this.GroupSelector = (InputFormCheckBoxList)TemplateContainer.FindControl("GroupSelector");
            if (this.GroupSelector == null)
                throw new ConfigurationErrorsException("Corrupted Controltemplate file.");

            if (!Page.IsPostBack)
            {
                List<int> ids = new List<int>();

                ///Elevated Rights, necessary because of using SPGroup.Users Property
                using (SPSite site = SPSecurityHelper.GetElevatedSite(SPContext.Current.Site))
                {
                    foreach (SPGroup group in site.OpenWeb(SPContext.Current.Web.ID).Groups)
                    {
                        int iUser = group.Users.Count;
                        if (group.ContainsCurrentUser)
                            iUser--;
                        ListItem item = new ListItem(group.Name + "</td><td>(" + iUser + ")", group.Name);
                        item.Attributes["class"] = "ms-RadioText";
                        // item.Attributes["style"] = "padding-left: 15px";
                        GroupSelector.Items.Add(item);
                        ids.Add(group.ID);
                    }
                }
            }
        }
    }
}
